;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.ServiceBorrowOut", [])
        .controller("ServiceBorrowOutCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "EventBus", "$filter", "UserContextService", "$stateParams", "MaterialService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, EventBus, $filter, UserContextService, $stateParams, MaterialService) {
            $scope.activeFlag = [true, false, false, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.deleteIdList = [];   // 要删除的零件id数组
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.submitted = false;
            $scope.condition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.dataList = [];
            $scope.outState = [
                {id: 0, name: "未出库"},
                {id: 1, name: "部分出库"},
                {id: 2, name: "已出库"},
                {id: 3, name: "强制结单"}
            ];
            $scope.reasonList = [];
            $scope.costPriceShow = false;
            $scope.tbConf = {
                fixedWidth: 340,
                scrollWidth: 1680,
                tableCol: [
                    {
                        type: "",
                        name: "服务人员借用单号",
                        dataField: "borrowNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务人员",
                        dataField: "serviceStaffName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发出仓库",
                        dataField: "warehouseCode",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "customerName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "原因",
                        dataField: "reason",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "派工单号",
                        dataField: "dispatchNo",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "remark",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务人员借用额度",
                        dataField: "borrowingQuota",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务人员欠款额度",
                        dataField: "arrears",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "statusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 300,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.newTbConf = {
                scrollWidth: 940,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 120,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "实际库存",
                        width: 100,
                        dataField: "enableNum",
                        input: false,
                        clickFn: "alterReport",
                        inputType: ""
                    },
                    {
                        name: "借用数量",
                        width: 150,
                        dataField: "quantity",
                        input: true,
                        inputType: "txt"
                    },
                    {
                        name: "单价",
                        width: 150,
                        dataField: "price",
                        input: false,
                        inputType: "price"
                    },
                    {
                        name: "小计",
                        width: 150,
                        dataField: "subtotalAmount",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "成本单价",
                        width: 150,
                        dataField: "costPrice",
                        input: false,
                        type: 'cost',
                        inputType: ""
                    },
                    {
                        name: "成本小计",
                        width: 150,
                        dataField: "costSubtotal",
                        input: false,
                        type: "cost",
                        inputType: ""
                    }
                ]
            };
            $scope.editTbConf = {
                scrollWidth: 1280,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 120,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "实际库存",
                        width: 120,
                        dataField: "enableNum",
                        clickFn: "alterReport",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "借用数量",
                        width: 150,
                        dataField: "quantity",
                        input: true,
                        inputType: "txt"
                    },
                    {
                        name: "单价",
                        width: 150,
                        dataField: "price",
                        input: false,
                        inputType: "price"
                    },
                    {
                        name: "小计",
                        width: 150,
                        dataField: "subtotalAmount",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "实际出库数量",
                        width: 110,
                        dataField: "outQuantity",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "转销售数量",
                        dataField: "resaleQty",
                        width: 100,
                        input: false,
                        // clickFn: "intentionDetail",
                        inputType: ""
                    },
                    {
                        name: "已退回数量",
                        dataField: "rollBackQty",
                        width: 100,
                        input: false,
                        // clickFn: "deliveryDetail",
                        inputType: ""
                    },
                    {
                        name: "状态",
                        width: 100,
                        dataField: "statusShow",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "成本单价",
                        width: 150,
                        dataField: "costPrice",
                        input: false,
                        type: "cost",
                        inputType: ""
                    },
                    {
                        name: "成本小计",
                        width: 150,
                        dataField: "costSubtotal",
                        input: false,
                        type: "cost",
                        inputType: ""
                    },
                ]
            };
            $scope.viewTbConf = {
                scrollWidth: 1460,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "实际库存",
                        width: 100,
                        dataField: "enableNum",
                        clickFn: "alterReport",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "借用数量",
                        width: 100,
                        dataField: "quantity",
                        input: true,
                        inputType: "txt"
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: true,
                        inputType: "price"
                    },
                    {
                        name: "小计",
                        width: 100,
                        dataField: "subtotalAmount",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "实际出库数量",
                        width: 110,
                        dataField: "outQuantity",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "转销售数量",
                        dataField: "resaleQty",
                        width: 100,
                        input: false,
                        // clickFn: "intentionDetail",
                        inputType: ""
                    },
                    {
                        name: "已退回数量",
                        dataField: "rollBackQty",
                        width: 100,
                        input: false,
                        // clickFn: "deliveryDetail",
                        inputType: ""
                    },
                    {
                        name: "状态",
                        width: 100,
                        dataField: "statusShow",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "成本单价",
                        width: 100,
                        dataField: "costPrice",
                        input: true,
                        inputType: "price",
                        type: "cost"
                    },
                    {
                        name: "成本小计",
                        width: 100,
                        dataField: "costSubtotal",
                        input: true,
                        inputType: "price",
                        type: "cost"
                    },
                ]
            };
            $scope.outTbConf = {
                scrollWidth: 770,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 120,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "出库数量",
                        width: 150,
                        dataField: "quantity",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "储位",
                        width: 150,
                        dataField: "locationCode",
                        input: true,
                        inputType: "func"
                    },
                    {
                        name: "出库状态",
                        width: 150,
                        dataField: "statusShow",
                        input: false,
                        inputType: ""
                    }
                    // ,
                    // {
                    //     name: "意向占用",
                    //     dataField: "intentionNum",
                    //     width: 100,
                    //     input: false,
                    //     clickFn: "intentionDetail",
                    //     inputType: ""
                    // },
                    // {
                    //     name: "发货占用",
                    //     dataField: "deliveryNum",
                    //     width: 100,
                    //     input: false,
                    //     clickFn: "deliveryDetail",
                    //     inputType: ""
                    // }
                ]
            };
            $scope.orderObj = {
                headerInfo: {},
                materialList: []
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/serviceBorrowOut/export"),
                sectionParam: {ids: []},
                allUrl: ybHttp.RequestUrl("device", "/serviceBorrowOut/exportAll")
            };
            $scope.tabFlag = {};

            var btnPermissionCode = {
                serviceBorrowOutAdd: window.ActionCode.serviceBorrowOutAdd,
                serviceBorrowOutEdit: window.ActionCode.serviceBorrowOutEdit,
                serviceBorrowOutDel: window.ActionCode.serviceBorrowOutDel,
                serviceBorrowOutPrint: window.ActionCode.serviceBorrowOutPrint,
                serviceBorrowOutOut: window.ActionCode.serviceBorrowOutOut,
                serviceBorrowOutExport: window.ActionCode.serviceBorrowOutExport,
                serviceBorrowOutToSale: window.ActionCode.serviceBorrowOutToSale,
                serviceBorrowOutToIn: window.ActionCode.serviceBorrowOutToIn,
                mandatoryFinish: window.ActionCode.serviceBorrowOutMandatoryFinish,
                showCostPrice: window.ActionCode.showCostPrice,
            };

            $scope.btnPermission = {
                serviceBorrowOutAdd: true,
                serviceBorrowOutEdit: true,
                serviceBorrowOutDel: true,
                serviceBorrowOutPrint: true,
                serviceBorrowOutOut: true,
                serviceBorrowOutExport: true,
                serviceBorrowOutToSale: true,
                serviceBorrowOutToIn: true,
                mandatoryFinish: true,
                showCostPrice: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    fixedWidth: {left: $scope.tbConf.fixedWidth + "px"}
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                $scope.deleteIdList = [];   // 清空要删除的零件id数组
                $scope.serviceStaffQuota = {};
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.orderObj = {
                    headerInfo: {},
                    materialList: []
                };
                $scope.tabFlag = {};
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/serviceBorrowOut/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate, "yyyy-MM-dd HH:mm:ss");
                        item.statusShow = $filter("ProgressStatus")(item.status, "outDepot");
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                    return resp.value.list
                });
            }

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    case "viewSapError":
                        viewSapError(item);
                        break;
                    case "alterReport":
                        alterReport(item);
                        break;
                    // case "intentionDetail":
                    //     intentionDetail(item);
                    //     break;
                    // case "deliveryDetail":
                    //     deliveryDetail(item);
                    //     break;
                    default:
                        break;
                }
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            $scope.applyOut = function () {
                $scope.tabFlag.type = 0;
                $scope.orderObj.headerInfo.createId = $scope.curUser.userId;
                $scope.orderObj.headerInfo.createName = $scope.curUser.name;
                $scope.orderObj.headerInfo.deptId = $scope.curUser.deptId;
                $scope.orderObj.headerInfo.dept = $scope.curUser.deptName;
                $scope.orderObj.headerInfo.applicationDate = +new Date();
                $scope.changeTab(1);
            };

            function getReason() {
                var service = "device";
                var reqUrl = "/serviceBasicDataAgent/searchList";
                var reqParam = {};
                reqParam.pCode = "BORROWREASON";
                ybHttp.Post(service, reqUrl, reqParam).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp);
                        return;
                    }
                    $scope.reasonList = resp.value;
                });
            }

            $scope.delData = function (delType, billId) {
                var service = "device";
                var reqUrl = "/serviceBorrowOut/delete";
                var billIds = [];
                if (delType === "single") {
                    billIds.push(billId);
                }
                if (delType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked) {
                            billIds.push($scope.dataList[i].id);
                        }
                    }
                }
                if (billIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, billIds).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.selectWarehouse = function () {
                ybWidget.WarehouseUsingSelector().then(function (data) {
                    if (!!$scope.orderObj.headerInfo.warehouseCode && (data.warehouseCode !== $scope.orderObj.headerInfo.warehouseCode)) {
                        // $scope.orderObj.headerInfo.outArea = "";
                        // $scope.orderObj.headerInfo.sapOutArea = "";
                        clearMateriel();
                    }
                    $scope.orderObj.headerInfo.warehouseCode = data.warehouseCode;
                })
            };

            $scope.clearWarehouse = function () {
                $scope.orderObj.headerInfo.warehouseCode = "";
                $scope.orderObj.headerInfo.outLocation = "";
                $scope.orderObj.headerInfo.outArea = "";
                $scope.orderObj.headerInfo.sapOutArea = "";
                clearMateriel();
            };

            $scope.selectArea = function () {
                if (!$scope.orderObj.headerInfo.outLocation) {
                    ybWidget.ShowToaster('error', '请选择调出仓库');
                    return;
                }
                var param = {};
                param.warehouseCode = $scope.orderObj.headerInfo.outLocation;
                ybWidget.DepotAreaSelector(param).then(function (data) {
                    if (!$scope.orderObj.headerInfo.outArea || (data.areaCode !== $scope.orderObj.headerInfo.outArea)) {
                        clearMateriel();
                    }
                    $scope.orderObj.headerInfo.outArea = data.areaCode;
                })
            };

            function alterReport(item) {
                var param = {
                    materialsNo: item.materialsNo
                };
                ybWidget.StorageReport(param);
            }

            $scope.clearArea = function () {
                $scope.orderObj.headerInfo.outArea = "";
                $scope.orderObj.headerInfo.sapOutArea = "";
                clearMateriel();
            };

            $scope.selectLogisticsCom = function () {
                var param = {
                    name: "承运物流",
                    type: "carrier"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.headerInfo.logistics = data.companyName;
                })
            };

            $scope.clearLogisticsCom = function () {
                $scope.orderObj.headerInfo.logistics = "";
            };

            $scope.selectAgent = function () {
                var param = {
                    name: "客户",
                    type: "dealer"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.headerInfo.customerName = data.companyName;
                    $scope.orderObj.headerInfo.customerId = data.dealerOrgId;
                })
            };

            $scope.clearAgent = function () {
                $scope.orderObj.headerInfo.customerName = "";
            };

            $scope.selMateriel = function (e) {
                if (!$scope.orderObj.headerInfo.warehouseCode) {
                    ybWidget.ShowToaster('warn', '请先选择仓库！');
                    return;
                }
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.importMateriel = function () {
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/serviceBorrowOutDetail/download",
                    importReqService: "device",
                    importReqUrl: "/serviceBorrowOutDetail/import",
                    importErrorUrl: "",
                    warehouseCode: $scope.orderObj.headerInfo.outLocation,
                    areaCode: $scope.orderObj.headerInfo.outArea
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                    });
                    $scope.orderObj.materialList = [];
                    $scope.orderObj.materialList = angular.copy(data);
                    setTotal();
                });
            };

            // 单个删除零件
            $scope.delMateriel = function (item, index) {
                if ($scope.orderObj.headerInfo.id) {
                    $scope.deleteIdList.indexOf(item.id) < 0 && $scope.deleteIdList.push(item.id);
                }
                $scope.orderObj.materialList.splice(index, 1);
                setTotal();
                EventBus.Publish("setMaterial", item.materialsNo);
            };

            // 删除零件接口
            function deleteMaterial(ids) {
                var url = "/serviceBorrowOutDetail/batchDelete";
                return ybHttp.Post('device', url, ids).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return false;
                    }
                    ybWidget.ShowToaster('success', '删除成功！');
                    return true;
                })
            }

            // 批量删除零件
            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                var ids = [];
                for (var i = $scope.orderObj.materialList.length - 1; i >= 0; i--) {
                    if (!!$scope.orderObj.materialList[i].isChecked) {
                        selectedCount++;
                        ids.push($scope.orderObj.materialList[i].id);
                        $scope.orderObj.materialList.splice(i, 1);
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                // 放入要删除的零件id数组 提交的时候接口删除
                if ($scope.orderObj.headerInfo.id) {
                    $scope.deleteIdList = ids;
                }
                // 全部删除的话 取消全选框选中状态
                if ($scope.orderObj.materialList.length === 0) {
                    $scope.markInfo.allCheckedMaterial = false;
                }
                setTotal();   // 设置总价
                EventBus.Publish("setMaterial");
            };

            function clearMateriel() {
                $scope.orderObj.materialList = [];
                $scope.markInfo.allCheckedMaterial = false;
                $timeout(function () {
                    if (!$scope.orderObj.headerInfo.outArea) {
                        EventBus.Publish("clearMaterial");
                    } else {
                        EventBus.Publish("getMaterial");
                    }
                });
            }

            function getDetail(billId) {
                var service = "device";
                var reqUrl = "/serviceBorrowOut/item";
                var param = {};
                param.id = billId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    angular.forEach(resp.value.serviceBorrowOutDetailVOS, function (item) {
                        item.statusShow = $filter("ProgressStatus")(item.status, "outDepot");
                        item.outPrice = item.price * item.realQty;

                        checkItemStockStatus(item, +item.quantity);
                    });
                    $scope.orderObj.headerInfo = resp.value;
                    $scope.orderObj.headerInfo.oldTotalAmount = resp.value.totalAmount;
                    $scope.orderObj.materialList = resp.value.serviceBorrowOutDetailVOS;
                    return resp.value;
                });
            }

            function viewDetail(item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.changeTab(3);
                });
            }

            function viewSapError(item) {
                ybWidget.ShowMessage(item.sapErrorMsg, MESG_TYPE.Note);
            }

            $scope.editData = function (item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    // 服务人员id
                    var staffId = $scope.orderObj.headerInfo.serviceStaffId;
                    // 获取服务人员额度
                    getServiceStaffQuotaDetail(staffId);
                    $scope.tabFlag.type = 1;
                    $scope.changeTab(2);
                });
            };

            $scope.checkStock = function (item) {
                item.quantityErr = false;
                if (!item.quantity || parseFloat(item.quantity) <= 0) {
                    item.quantityErr = true;
                    item.quantityErrMsg = "借用数量不能为空和0";
                    return;
                }
                if (parseFloat(item.quantity) < parseFloat(item.outQuantity)) {
                    item.quantityErr = true;
                    item.quantityErrMsg = "借用数量不能小于实际出库数量";
                    return;
                }
                if (item.quantity > 99999.999) {
                    item.quantity = 99999.999;
                }
                item.outPrice = $filter("decimalCover")(ybWidget.Times(item.realQty, item.price), 2);
                item.subtotalAmount = $filter("decimalCover")(ybWidget.Times(item.quantity, item.price), 2);
                item.costSubtotal = $filter("decimalCover")(ybWidget.Times(item.quantity, item.costPrice), 2);
                checkItemStockStatus(item, +item.quantity);
                setTotal();
            };

            function checkItemStockStatus(item, currentQty) {
                UserContextService.SetStockStatusFlag(item, currentQty);
            }

            $scope.showQtyTip = function (item) {
                if (!!item.quantityStockErr) {
                    item.showStockErr = true;
                }
            };
            $scope.hideQtyTip = function (item) {
                item.showStockErr = false;
            };
            $scope.printBill = function (item) {
                var id = item.id;
                var billIds = [];
                billIds.push(id);
                var param = {
                    billId: billIds,
                    printType: "ServiceBorrowOut"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            function checkListValid() {
                var isValid = true;
                for (var i = 0, len = $scope.orderObj.materialList.length; i < len; i++) {
                    if ($scope.orderObj.materialList[i].quantityErr) {
                        isValid = false;
                        break;
                    }
                    if (!$scope.orderObj.materialList[i].quantity || parseFloat($scope.orderObj.materialList[i].quantity) <= 0) {
                        isValid = false;
                        $scope.orderObj.materialList[i].quantityErr = true;
                        $scope.orderObj.materialList[i].quantityErrMsg = "借用数量不能为空和0";
                        break;
                    }
                    if (parseFloat($scope.orderObj.materialList[i].quantity) < parseFloat($scope.orderObj.materialList[i].outQuantity)) {
                        isValid = false;
                        $scope.orderObj.materialList[i].quantityErr = true;
                        $scope.orderObj.materialList[i].quantityErrMsg = "借用数量不能小于实际出库数量";
                        break;
                    }
                    // if (parseFloat($scope.orderObj.materialList[i].quantity) > parseFloat($scope.orderObj.materialList[i].enableNum)) {
                    //     isValid = false;
                    //     $scope.orderObj.materialList[i].quantityErr = true;
                    //     $scope.orderObj.materialList[i].quantityErrMsg = "借用数量不能大于实际库存数量";
                    //     break;
                    // }
                }
                return isValid;
            }

            //检查是否超过服务人员借用额度
            function checkServiceStaffQtota() {
                //是编辑还是新增
                var isEdit = !!$scope.orderObj.headerInfo.id;
                //如果没有设置借用额度就直接返回
                if (!$scope.serviceStaffQuota || $scope.serviceStaffQuota.restBorrowAmount === undefined) return false;
                // 服务人员剩余借用额度
                var restBorrowAmount = parseFloat($scope.serviceStaffQuota.restBorrowAmount);
                if (!isEdit && restBorrowAmount <= 0) return true;
                // 订单总计
                var totalAmount = parseFloat($scope.orderObj.headerInfo.totalAmount);
                // 订单编辑前的总价
                var oldTotalAmount = parseFloat($scope.orderObj.headerInfo.oldTotalAmount || 0);
                //剩余额度小于总价则超出额度  编辑的时候服务人员的剩余额度是加上订单原来的总价的和
                if (!isEdit && restBorrowAmount < totalAmount) {
                    return true;
                }
                if (!!isEdit && restBorrowAmount + oldTotalAmount < totalAmount) {
                    return true;
                }
                return false;
            }

            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                if ($scope.orderObj.materialList.length === 0) {
                    ybWidget.ShowToaster('error', '零件不可为空');
                    return;
                }
                var listValid = checkListValid();
                if (!listValid) {
                    return;
                }
                //检查是否超出服务人员借用额度
                var outQuota = checkServiceStaffQtota();
                if (outQuota) {
                    ybWidget.ShowMessage("零件总价已超过服务人员剩余借用额度，是否确定还要继续提交？", MESG_TYPE.Ask).then(function () {
                        saveServiceBorrowOut();
                    });
                } else {
                    saveServiceBorrowOut();
                }
            };

            //调接口保存服务借用单
            function saveServiceBorrowOut() {
                var service = "device";
                var reqUrl = "/serviceBorrowOut/save";
                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/serviceBorrowOut/save";
                }
                var param = angular.copy($scope.orderObj.headerInfo);
                if ($scope.deleteIdList.length > 0) {
                    param.deleteIdList = $scope.deleteIdList;
                }
                param.serviceBorrowOutDetailVOS = $scope.orderObj.materialList;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if ($scope.tabFlag.type === 0) {
                        getDataList(1);
                    } else {
                        getDataList();
                    }
                    $scope.changeTab(0);
                });
            }

            $scope.outbound = function (item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.changeTab(4);
                });
            };

            // 批量选择储位
            $scope.multiSelDepot = function () {
                var warehouseCode = $scope.orderObj.headerInfo.warehouseCode;
                var list = $scope.orderObj.materialList;
                MaterialService.multiSelDepot(warehouseCode, list);
            };

            $scope.selDepot = function (item) {
                var param = {
                    warehouseCode: $scope.orderObj.headerInfo.warehouseCode
                };
                ybWidget.DepotSelector(param).then(function (data) {
                    item.warehouseCode = data.warehouseCode;
                    item.areaCode = data.areaCode;
                    item.locationCode = data.locationCode;
                })
            };

            $scope.clearDepot = function (item) {
                item.warehouseCode = "";
                item.areaCode = "";
                item.locationCode = "";
            };

            $scope.outboundSubmit = function () {
                var service = "device";
                var reqUrl = "/warehouseDeliveryRecord/receive";
                var param = {
                    headerInfo: {},
                    detailList: []
                };
                var errorCount = 0;
                param.headerInfo.businessOrder = $scope.orderObj.headerInfo.borrowNo;
                angular.forEach($scope.orderObj.materialList, function (item) {
                    var listRow = {};
                    listRow.materialNo = item.materialsNo;
                    listRow.warehouseCode = item.warehouseCode;
                    listRow.areaCode = item.areaCode;
                    listRow.locationCode = item.locationCode;
                    item.locationErr = false;
                    if ((item.status === 0 || item.status === 1) && !item.locationCode) {
                        item.locationErr = true;
                        errorCount++;
                    }
                    param.detailList.push(listRow);
                });
                if (errorCount > 0) {
                    return;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            $scope.obligate = function (item) {
                $state.go("app.sales.salesOrder", {borrowId: item.id})
            };

            // 转退回
            $scope.goReturn = function (item) {
                $state.go("app.sales.serviceBorrowIn", {borrowId: item.borrowNo})
            };

            $scope.posting = function (item, materialsNo) {
                ybWidget.ShowMessage("确定要过账吗？", MESG_TYPE.Ask).then(function () {
                    item.postingDisabled = true;
                    var service = "device";
                    var reqUrl = "/warehouseInventory/obligatePosting";
                    var param = {};
                    param.businessOrder = item.borrowNo;
                    param.materialsNo = materialsNo;
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            item.postingDisabled = false;
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!item.id) {
                            getDetail(item.id);
                        }
                        getDataList();
                    });
                }, function () {
                });
            };

            $scope.deliveryRevoke = function (item, materialsNo) {
                ybWidget.ShowMessage("确定要撤回吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/warehouseInventory/deliveryRevoke";
                    var param = {
                        businessOrder: item.borrowNo,
                        materialsNo: materialsNo ? materialsNo : null
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!item.id) {
                            getDetail(item.id);
                        }
                        getDataList();
                    });
                }, function () {
                });
            };

            $scope.mandatoryFinish = function (billNo, billId, materialsNo) {
                ybWidget.ShowMessage("确定要结单吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/serviceBorrowOut/manualFinish";
                    var param = {
                        billNo: billNo,
                        materialsNo: materialsNo ? materialsNo : null
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!billId) {
                            getDetail(billId);
                        }
                        getDataList();
                    });
                }, function () {
                });
            };


            EventBus.Subscribe("onMaterialChange", setTotal);

            function setTotal() {
                var totalPrice = 0;
                var costTotal = 0;
                angular.forEach($scope.orderObj.materialList, function (item) {
                    item.subtotalAmount = $filter("decimalCover")(ybWidget.Times(item.quantity, item.price), 2);
                    totalPrice = $filter("decimalCover")(ybWidget.Plus(totalPrice, parseFloat(item.subtotalAmount)), 2);
                    costTotal = $filter("decimalCover")(ybWidget.Plus(costTotal, parseFloat(item.costSubtotal)), 2);
                });
                $scope.orderObj.headerInfo.totalAmount = totalPrice;
                $scope.orderObj.headerInfo.costTotal = costTotal;
            };

            $scope.searchDispatch = function () {
                var type = "servicer";
                var param = {
                    name: "服务人员",
                    type: type,
                    supplierOrgId: $scope.curUser.spaceId,
                    roleName: "服务人员"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.headerInfo.serviceStaffName = data.name;
                    $scope.orderObj.headerInfo.serviceStaffId = data.userId;
                    $scope.serviceStaffQuota = {};
                    getServiceStaffQuotaDetail(data.userId);
                })
            };

            //获取服务人员借用额度
            function getServiceStaffQuotaDetail(userId) {
                var url = '/serviceStaffQuota/item';
                var param = {
                    userId: userId
                };
                $scope.serviceStaffQuota = {};   // 清空服务人员额度信息
                ybHttp.Get('device', url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    // 如果服务人员的额度为禁用状态 则直接返回
                    if (!res.value || !res.value.borrowingQuota || res.value.status === 0) return;
                    res.value.restBorrowAmount = parseFloat(res.value.borrowingQuota) - parseFloat(res.value.borrowedAmount || 0);
                    $scope.serviceStaffQuota = res.value;
                })
            }

            (function () {
                var serviceBorrowOutBillNo = window.sessionStorage.getItem("serviceBorrowOutBillNo");
                window.sessionStorage.removeItem("serviceBorrowOutBillNo");
                if (!!serviceBorrowOutBillNo) {
                    $scope.condition.borrowNo = serviceBorrowOutBillNo;
                    getDataList().then(function (data) {
                        viewDetail(data[0]);
                    })
                } else {
                    getDataList();
                }
                getReason();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);
